window.onload = function() {
    const $ = name => document.querySelector(name);
    var token1 = window.localStorage.getItem('token');
    var logging = $('.logging');
    var mask = $('.wrapper');
    var loginbtn1 = document.getElementById('loginbtn1');
    var loginbtn2 = document.getElementById('loginbtn2');
    var loginbtn3 = document.getElementById('loginbtn3');
    var rlogo = document.getElementById('rlogo');
    var userinfo = document.getElementById('userinfo');
    var no_login = document.getElementById('no-login');
    var course_content = document.getElementById('course-content');
    var dropbtn = $('.dropdown');
    var teacherlogo = document.getElementById('teachercentre');
    axios.defaults.timeout = 5500;
    axios.defaults.baseURL = 'http://120.24.80.83:3000';
    // axios.defaults.headers.common['Authorization'] = token1;
    axios.interceptors.request.use(function(config) {
        // 在发送请求之前做些什么
        // 若token存在， 则在每次请求头中加入token
        if (window.localStorage.getItem('token')) {
            config.headers.Authorization = window.localStorage.getItem('token');
            // axios.defaults.headers.common['Authorization'] = window.localStorage.getItem('token');
        }
        // console.log(config);
        return config;
    }, function(error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });
    axios.interceptors.response.use(
            response => {
                if (getCookie("init")) {
                    var cookie = JSON.parse(getCookie("init"));
                } else {
                    var cookie = new Object();
                    var cookie = {
                        name: '',
                        pass: ''
                    };
                }
                if (response.data.msg == '登录失效' && (cookie.name == '' && cookie.pass == '')) {
                    // 这里写清除token的代码
                    // 清除token
                    console.log(response.data.msg);
                    setTimeout(() => {
                        // window.open('login.html');
                        loginbtn1.style.display = 'block';
                        loginbtn2.style.display = 'block';
                        loginbtn3.style.display = 'block';
                        rlogo.style.display = 'none';
                        no_login.style.display = 'block';
                        course_content.style.display = 'none';
                        userinfo.style.display = 'none';
                        userinfo.style.height = '0';
                    }, 3000);
                    // window.localStorage.removeItem('token');
                    console.log('登录过期，请重新登录');
                    Message({
                        message: '登录过期，请重新登录',
                        duration: 1000,
                        forbidClick: true
                    });
                    Message();
                    // window.location.href = 'login.html';
                }
                return response;
            },
            error => {
                if (error.response) {
                    switch (error.response.status) {
                        case 403:
                            // 这里写清除token的代码
                            console.log('清除token');
                            id1 = '';
                            Message({
                                message: '登录过期，请重新登录',
                                duration: 1000,
                                forbidClick: true
                            });
                            // 清除token
                            window.loaclStorage.removeItem('token');
                            break;
                    }
                }
                return Promise.reject(error.response.data)
            }
        )
        //页面加载时，如果有记录7天免登录
    if (getCookie("init")) {
        var cookie = JSON.parse(getCookie("init"));
        if (cookie.name != '' && cookie.pass != '') {
            axios({
                    url: "/login",
                    method: "post",
                    data: {
                        "username": cookie.name,
                        "password": cookie.pass,
                    }
                })
                .then(function(response) {
                    console.log(response.data);
                    var res = response.data.data;
                    personBusi();
                    //使用loackstorge保存token，方便以后需要的时候用
                    window.localStorage.setItem("token", res.token);
                    loginbtn1.style.display = 'none';
                    loginbtn2.style.display = 'none';
                    loginbtn3.style.display = 'none';
                    rlogo.style.display = 'block';
                    no_login.style.display = 'none';
                    userinfo.style.display = 'block';
                    course_content.style.display = 'block';
                    dropbtn.style.display = 'inline-block';
                    if (window.localStorage.getItem('avatar')) {
                        $('#rlogo img').src = window.localStorage.getItem('avatar');
                    }
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res.username;
                    if (res.avatar) {
                        $('#rlogo img').src = res.avatar;
                    } else {
                        $('#rlogo img').src = "img/register.png";
                    }
                    if (res.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                })
        } else {
            console.log('cookie已注销');
            dropbtn.style.display = 'none';
        }
    }
    Getquestion();
    //封装每隔五分钟发送请求的函数
    function personBusi() {
        var cookie = JSON.parse(getCookie("init"));
        setTimeout(personBusi, 1000 * 60 * 5); //这里的1000表示1秒有1000毫秒,1分钟有60秒,5表示总共5分钟 
        axios({
                url: "/login",
                method: "post",
                data: {
                    "username": cookie.name,
                    "password": cookie.pass,
                }
            })
            .then(response => {
                if (response.data.code == 1) {
                    var res1 = response.data.data;
                    console.log('刷新token');
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    dropbtn.style.display = 'inline-block';
                    window.localStorage.removeItem("token");
                    window.localStorage.setItem("token", res1.token);
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res1.username;
                    if (res1.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res1.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                    if (res1.avatar) {
                        document.querySelector(".pic img").src = res1.avatar;
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                }
            })

    }
    //验证token是否失效
    if (window.localStorage.getItem("token")) {
        axios({
            method: 'post',
            url: '/refresh',
        }).then(response => {
            var res = response.data;
            console.log(res);
            if (res.code == 1) {
                console.log('token有效');
                var id3 = window.localStorage.getItem('username');
                loginbtn1.style.display = 'none';
                loginbtn2.style.display = 'none';
                loginbtn3.style.display = 'none';
                userinfo.style.display = 'block';
                no_login.style.display = 'none';
                course_content.style.display = 'block';
                rlogo.style.display = 'block';
                dropbtn.style.display = 'inline-block';
                var role3 = window.localStorage.getItem('role');
                document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + id3;
                if (role3 == 'teacher') {
                    teacherlogo.style.display = 'block';
                    document.getElementById('rolelogo').innerHTML = '教师';
                } else if (role3 == 'student') {
                    teacherlogo.style.display = 'none';
                    document.getElementById('rolelogo').innerHTML = '学生';
                }
                rlogo.style.display = 'block';
                if (window.localStorage.getItem('avatar')) {
                    $('#rlogo img').src = window.localStorage.getItem('avatar');
                } else {
                    $('#rlogo img').src = "img/register.png";
                }
                document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + id3;
            } else {
                console.log('error');
            }

        }).catch(err => {

        })
    }
    //登录

    var login = document.getElementById('submit');
    var username = document.getElementById('username');
    var password = document.getElementById('password');
    var role = '';
    var role1 = '';
    var token1 = '';
    var id1 = '';
    var avatar = '';
    var name1 = '';

    login.addEventListener('click', function() {

            var un1 = username;
            var pw1 = password;
            axios({
                method: 'post',
                url: '/login',
                data: {
                    username: un1.value,
                    password: pw1.value,
                } //params是拼接参数请求，而data是把参数放进请求体
            }).then(response => {
                var res = response.data;
                console.log(res);
                if (res.code == 1) {
                    console.log('登录成功');
                    $('.aftertips').innerHTML = '√ 登录成功！';
                    successtip();
                    Getquestion();
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res.data.username;
                    document.getElementById('loginbtn3').disabled = false;
                    window.localStorage.removeItem('token');
                    window.localStorage.removeItem('role');
                    window.localStorage.removeItem('id');
                    window.localStorage.removeItem('username');
                    window.localStorage.removeItem('avatar');
                    loginbtn1.style.display = 'none';
                    loginbtn2.style.display = 'none';
                    loginbtn3.style.display = 'none';
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    no_login.style.display = 'none';
                    course_content.style.display = 'block';
                    logging.style.display = 'none';
                    mask.style.display = 'none';
                    dropbtn.style.display = 'inline-block';
                    console.log('欢迎' + res.data.username);
                    token1 = res.data.token;
                    id1 = res.data.id;
                    role = res.data.role;
                    name1 = res.data.username;
                    if (res.data.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res.data.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                    if (res.data.avatar) {
                        avatar = res.data.avatar;
                        window.localStorage.setItem('avatar', avatar);
                        document.querySelector('#rlogo img').src = window.localStorage.getItem('avatar');
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                    // console.log(token1);
                    if (token1) {
                        // window.localStorage.removeItem('token');
                        window.localStorage.setItem('token', token1);
                        window.localStorage.setItem('role', role);
                        window.localStorage.setItem('id', id1);
                        window.localStorage.setItem('username', name1);
                    }
                } else if (res.msg = '用户名或密码错误') {
                    document.getElementById('error').innerHTML = '用户名或密码错误';
                    setTimeout(() => {
                        document.getElementById('error').innerHTML = '';
                    }, 2000);
                    console.log('error');
                }

            })
        })
        //注册
    var register1 = document.querySelector('#register1');
    var username1 = document.querySelector('#username1');
    var password1 = document.querySelector('#password1');
    var teacher = document.querySelector('#teacher');
    var student = document.querySelector('#student');

    teacher.addEventListener('change', function() {
        if (this.checked) {
            role1 = 'teacher';
        }
    })
    student.addEventListener('change', function() {
        if (this.checked) {
            role1 = 'student';
        }
    })

    register1.addEventListener('click', function() {

            var un2 = username1;
            var pw2 = password1;
            axios({
                method: 'post',
                url: '/register',
                data: {
                    username: un2.value,
                    password: pw2.value,
                    role: role1
                } //params是拼接参数请求，而data是把参数放进请求体
            }).then(response => {
                var res = response.data;
                console.log(res);
                if (res.code == 1) {
                    $('.aftertips').innerHTML = '√ 注册成功！';
                    successtip();
                    console.log('注册成功');
                    document.getElementById('error1').innerHTML = '注册成功';
                } else if (res.msg = '该用户已经被注册过了') {
                    document.getElementById('error1').innerHTML = '该用户名已被使用';
                    $('.aftertips').innerHTML = '× 注册失败！';
                    errtip();
                    setTimeout(() => {
                        document.getElementById('error1').innerHTML = '';
                        var u = document.getElementById('username1');
                        u.value = '';
                        var p = document.getElementById('password1');
                        p.value = '';
                    }, 2000)

                    console.log('error');
                }

            })
        })
        //七天免登录
        //设置cookie
    function setCookie(_name, val, expires) {
        var d = new Date();
        d.setDate(d.getDate() + expires);
        document.cookie = _name + "=" + val + ";path=/;expires=" + d.toGMTString();
    }

    //获取cookie
    function getCookie(_name) {
        var cookie = document.cookie;
        var arr = cookie.split("; ");
        for (var i = 0; i < arr.length; i++) {
            var newArr = arr[i].split("=");
            if (newArr[0] == _name) {
                return newArr[1];
            }
        }
    }
    /*
       如何将json对象转换为字符串
           JSON.stringify(对象);
           返回值是一个字符串
       如何将字符串转换为json对象
           JSON.parse(字符串)
           返回值是对象
    */

    var oBtn = document.getElementById("submit");
    var oUser = document.getElementById("username");
    var oPass = document.getElementById("password");
    var oCheck = document.getElementById("check1");

    if (getCookie("init")) {
        var cookie = JSON.parse(getCookie("init"));
        oUser.value = cookie.name;
        oPass.value = cookie.pass;
        oCheck.checked = true;
    }

    oBtn.onclick = function() {
        if (oCheck.checked) {
            var obj = {};
            obj.name = oUser.value;
            obj.pass = oPass.value;
            var str = JSON.stringify(obj);
            setCookie("init", str, 7);
        }
    }

    //退出登录的函数
    function Outlogin() {
        loginbtn1.style.display = 'block';
        loginbtn2.style.display = 'block';
        loginbtn3.style.display = 'block';
        rlogo.style.display = 'none';
        no_login.style.display = 'block';
        course_content.style.display = 'none';
        userinfo.style.display = 'none';
        teacherlogo.style.display = 'none';
        dropbtn.style.display = 'none';
        window.localStorage.removeItem("token");
        $('.aftertips').innerHTML = '√ 退出成功！';
        successtip();
        var obj = {};
        obj.name = '';
        obj.pass = '';
        var str = JSON.stringify(obj);
        setCookie("init", str, 0.000001);
    }

    //退出登录
    document.querySelector("#out-login").addEventListener('click', function() {
        Outlogin();
    })
    var item = document.getElementsByClassName("item");
    var it = item[0].getElementsByTagName("div");
    var content = document.getElementsByClassName("content");
    var con = content[0].getElementsByTagName("div");
    for (let i = 0; i < it.length; i++) {
        it[i].onclick = function() {
            for (let j = 0; j < it.length; j++) {
                it[j].className = '';
                con[j].style.display = "none";
            }
            this.className = "active";
            it[i].index = i;
            con[i].style.display = "block";
        }
    }
    var closebtn1 = $('.closebtn');
    var login = $('.logging');
    var loginbtn = $('.btn-center');
    var link1 = $('#loginbtn1');
    var link2 = $('#loginbtn2');
    var link3 = $('#loginbtn3');
    var mask = $('.wrapper');
    var back = $('#backbtn');
    var tipbtn = $('#tipbtn');
    var area = $('.areatip');
    var postbtn = $('#postaction');
    var postcontent = $('.edittip');
    back.addEventListener('click', function() {
        tipbtn.style.display = 'block';
        area.style.height = '0.01px';
        area.style.visibility = 'hidden';
        postcontent.value = '';
    })
    tipbtn.addEventListener('click', function() {
        tipbtn.style.display = 'none';
        area.style.height = '280px';
        area.style.transition = 'height 1s ease-out';
        setTimeout(function() {
            area.style.visibility = 'visible';
        }, 700);
    })
    loginbtn.addEventListener('click', function() {
        login.style.display = 'block';
        mask.style.display = 'block';
        setTimeout(function() {
            login.style.opacity = 1;
        }, .1);
    })
    link1.addEventListener('click', function() {
        login.style.display = 'block';
        mask.style.display = 'block';
        setTimeout(function() {
            login.style.opacity = 1;
        }, .1);

    })
    link2.addEventListener('click', function() {
        login.style.display = 'block';
        mask.style.display = 'block';
        setTimeout(function() {
            login.style.opacity = 1;
        }, .1);

    })
    link3.addEventListener('click', function() {
        login.style.display = 'block';
        mask.style.display = 'block';
        setTimeout(function() {
            login.style.opacity = 1;
        }, .1);

    })
    closebtn1.addEventListener('click', function() {
        mask.style.display = 'none';
        login.style.opacity = 0;
        login.style.display = 'none';
    })

    function successtip() {
        var tips = $('.aftertips');
        tips.style.opacity = '1';
        tips.style.top = '60px';
        tips.style.color = '#67c23a';
        console.log('成功');
        setTimeout(function() {
            tips.style.opacity = '.2';
            tips.style.top = '-60px';
        }, 1800)
    }
    //搜索功能模块
    var search_input = $('.search-input');
    var search_content = $('.search-content');
    var search_box = $('.search');
    search_input.addEventListener('input', function() {
        var value = this.value.replace(/\s/g, '')
        if (value != '') {
            search(value);
        } else {
            clearTimeout(timer);
            $('.search-content').style.display = 'none';
            search_content.innerHTML = '';
        }
    })
    search_input.addEventListener('focus', function() {
        this.style.color = '#333'
    })
    search_input.addEventListener('blur', function() {
        this.style.color = '#999'
        setTimeout(() => {
            search_input.value = '';
        }, 1000);
    })
    search_box.addEventListener('click', function(e) {
        e.stopPropagation()
        var value = search_input.value.replace(/\s/g, '')
        if (value != '') {
            search_content.style.height = '320px';
            $('.search-content').style.display = 'block';
        }
    })
    document.addEventListener('click', function() {
        search_content.style.display = 'none';
    })
    var to_search = $('.to_search');
    to_search.addEventListener('click', function() {
        var value = search_input.value.replace(/\s/g, '');
        if (value != '') {
            window.localStorage.title = value;
            window.location.href = '../Searchcourse/searchcourse.html';
        }
    })
    window.addEventListener('keyup', function(e) {
            if (e.keyCode == 13 && search_input.value != '' && search_input == document.activeElement) {
                to_search.click()
            }
        })
        //利用防抖函数优化搜索课程功能
    var timer = null

    function search(value) {
        clearTimeout(timer)
        timer = setTimeout(function() {
            axios({
                url: '/course/search',
                params: {
                    title: value
                }
            }).then(response => {
                if (response.data.msg == '查找成功') {
                    var data = response.data.data
                    var str = ''
                    for (var k in data) {
                        str +=
                            `<li courseid="` + data[k].id + `">
                         <img src="` + data[k].image + `" alt="">
                         <div class="course-info">
                             <h2 class="course-title">` + data[k].title + `</h2>
                             <div class="teacher-info">
                                 <span class="teacher-name">` + data[k].teacherName + `</span>
                                 <span class="teacher-work">` + data[k].teacherTitle + `</span>
                             </div>
                         </div>
                     </li>`
                    }
                    search_content.innerHTML = str;
                    var course_titles = search_content.querySelectorAll('.course-title');
                    var course_titles_len = course_titles.length;
                    var teacher_names = document.querySelectorAll('.teacher-name');
                    var teacher_works = document.querySelectorAll('.teacher-work');
                    var reg = new RegExp(value, "g");
                    for (var i = 0; i < course_titles_len; i++) {
                        course_titles[i].innerHTML = course_titles[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                        teacher_names[i].innerHTML = teacher_names[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                        teacher_works[i].innerHTML = teacher_works[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                    }
                    $('.search-content').style.display = 'block';
                }
                console.log(response.data);
                var li1 = document.querySelectorAll('li');
                for (let t = 0; t < li1.length; t++) {
                    li1[t].addEventListener('click', function() {
                        window.localStorage.setItem('courseid', li1[t].getAttribute('courseid'));
                        Ifbuy();
                    })
                }
            }).catch(err => {
                console.log(err);
            })
            console.log(value)
        }, 800)
    }
    var searchresult = $('.showresult');
    //滚动条事件小火箭平滑运行
    var obtn = document.getElementById('return_top'); //获取回到顶部按钮的ID
    var clientHeight = document.documentElement.clientHeight; //获取可视区域的高度
    var timer = null; //定义一个定时器
    var isTop = true; //定义一个布尔值，用于判断是否到达顶部

    window.onscroll = function() { //滚动条滚动事件

        //获取滚动条的滚动高度
        var osTop = document.documentElement.scrollTop || document.body.scrollTop;

        if (osTop >= clientHeight) { //如果滚动高度大于可视区域高度，则显示回到顶部按钮
            obtn.style.display = 'block';
        } else { //否则隐藏
            obtn.style.display = 'none';
        }

        //主要用于判断当 点击回到顶部按钮后 滚动条在回滚过程中，若手动滚动滚动条，则清除定时器
        if (!isTop) {
            clearInterval(timer);
        }
        isTop = false;
    }
    obtn.onclick = function() { //回到顶部按钮点击事件
            //设置一个定时器
            timer = setInterval(function() {
                //获取滚动条的滚动高度
                var osTop = document.documentElement.scrollTop || document.body.scrollTop;
                //用于设置速度差，产生缓动的效果
                var speed = Math.floor(-osTop / 6);
                document.documentElement.scrollTop = document.body.scrollTop = osTop + speed;
                isTop = true; //用于阻止滚动事件清除定时器
                if (osTop == 0) {
                    clearInterval(timer);
                }
            }, 30);
        }
        //  操作失败后的提示信息
    function errtip() {
        var tips = $('.aftertips')
        tips.style.opacity = '1';
        tips.style.top = '60px';
        tips.style.color = '#f02019';
        setTimeout(function() {
            tips.style.opacity = '.2';
            tips.style.top = '-60px';
        }, 1800)
    }
    var num = document.getElementsByTagName('ul');
    console.log(num.length);
    var content_ = $('.questionlist');
    //封装获取问题列表的函数
    function Getquestion() {
        axios({
            method: 'get',
            url: '/question/getAllQuestion',

        }).then(response => {
            var res = response.data.data;
            var length = res.length;
            $('.anum').innerHTML = '(共' + length + '条)';
            console.log(res[0].reply[0]);
            content_.innerHTML = '';
            for (let t = length - 1; t >= 0; t--) {
                var ul = document.createElement("ul");
                ul.className = "qa";
                var str1 = '';
                var str = '';
                if (res[t].user.avatar) {
                    if (res[t].reply.length <= 5) {
                        for (let j = 0; j < res[t].reply.length; j++) {
                            str1 += '★';
                        }
                        for (let z = 0; z < 5 - res[t].reply.length; z++) {
                            str1 += '☆';
                        }
                    } else {
                        for (let j = 0; j < 5; j++) {
                            str1 += '★';
                        }
                    }
                    str += ` <li class="container" toId=${res[t].user.id} questionId=${res[t].id}>
                    <div class="imgbox">
                <img src="${res[t].user.avatar}" alt="" class="avatar">
                <div class="user_name">学生： <br>${res[t].user.username}</div>
                <div class="idbox">id:${res[t].user.id}</div>
                </div>
                <div class="question">问题：<br><div class="c1">${res[t].content}</div>
                <div class="time">${timeOperation(res[t].user.create_time)}</div></div>
                <div class="pnum">讨论次数：${res[t].reply.length}<br>热度：<br>${str1}</div>
            </li> <ul class="answerarea"><div class="detailquestion">
            <div class="title1">VIP教师回复<div class="return">收起</div></div>
            <div class="reply">
                <textarea name="" cols="" rows="" class="edittip1" placeholder="请输入回复的内容"></textarea>
                <div class="btnlist1">
                    <div class="postreply">确认发送</div>
                    <div class="cancelpost">取消</div>
                </div>
            </div>`;
                    for (let k in res[t].reply) {
                        if (res[t].reply[k].user.avatar) {
                            str += `
                        <li class="replymsg">
                        <div class="leftcontent">
                        <img src="${res[t].reply[k].user.avatar}" alt="" class="replyerimg">
                        <div class="replyname">教师：<br>${res[t].reply[k].user.username}</div>
                        </div>
                        <div class="rightcontent">
                        <div class="replycontent">回复：(${res[t].user.username})<br>${res[t].reply[k].content}</div>
                        <div class="replytime">${timeOperation(res[t].reply[k].user.create_time)}</div>
                        </div>
                    </li> `;
                        } else {
                            str += `
                <li class="replymsg">
                <div class="leftcontent">
                <img src="img/register.png" alt="" class="replyerimg">
                <div class="replyname">教师：<br>${res[t].reply[k].user.username}</div>
                </div>
                <div class="rightcontent">
                <div class="replycontent">回复：(${res[t].user.username})<br>${res[t].reply[k].content}</div>
                <div class="replytime">${timeOperation(res[t].reply[k].user.create_time)}</div>
                </div>
            </li> `;

                        }

                    }
                    str += `</div></ul>`;
                    ul.innerHTML = str;
                    content_.append(ul);
                    // answer_[t].innerHTML = str2;
                } else {
                    var str1 = '';
                    if (res[t].reply.length <= 5) {
                        for (let j = 0; j < res[t].reply.length; j++) {
                            str1 += '★';
                        }
                        for (let z = 0; z < 5 - res[t].reply.length; z++) {
                            str1 += '☆';
                        }
                    } else {
                        for (let j = 0; j < 5; j++) {
                            str1 += '★';
                        }
                    }
                    str += ` <li class="container" toId=${res[t].user.id} questionId=${res[t].id}>
                    <div class="imgbox">
                <img src="img/register.png" alt="" class="avatar">
                <div class="user_name">学生： <br>${res[t].user.username}</div>
                <div class="idbox">id:${res[t].user.id}</div>
                </div>
                <div class="question">问题：<br><div class="c1">${res[t].content}</div>
                <div class="time">${timeOperation(res[t].user.create_time)}</div></div>
                <div class="pnum">讨论次数：${res[t].reply.length}<br>热度：<br>${str1}</div>
            </li><ul class="answerarea"><div class="detailquestion">
            <div class="title1">VIP教师回复<div class="return">收起</div></div>
            <div class="reply">
                <textarea name="" cols="" rows="" class="edittip1" placeholder="请输入回复的内容"></textarea>
                <div class="btnlist1">
                    <div class="postreply">确认发送</div>
                    <div class="cancelpost">取消</div>
                </div>
            </div>`;
                    for (let k in res[t].reply) {
                        if (res[t].reply[k].user.avatar) {
                            str += `
                            <li class="replymsg">
                            <div class="leftcontent">
                            <img src="${res[t].reply[k].user.avatar}" alt="" class="replyerimg">
                            <div class="replyname">教师：<br>${res[t].reply[k].user.username}</div>
                            </div>
                            <div class="rightcontent">
                            <div class="replycontent">回复：(${res[t].user.username})<br>${res[t].reply[k].content}</div>
                            <div class="replytime">${timeOperation(res[t].reply[k].user.create_time)}</div>
                            </div>
                        </li> `;
                        } else {
                            str += `
                    <li class="replymsg">
                    <div class="leftcontent">
                    <img src="img/register.png" alt="" class="replyerimg">
                    <div class="replyname">教师：<br>${res[t].reply[k].user.username}</div>
                    </div>
                    <div class="rightcontent">
                    <div class="replycontent">回复：(${res[t].user.username})<br>${res[t].reply[k].content}</div>
                    <div class="replytime">${timeOperation(res[t].reply[k].user.create_time)}</div>
                    </div>
                </li> `;

                        }

                    }
                    str += `</div></ul>`;
                    ul.innerHTML = str;
                    content_.append(ul);
                }
            }
            Spreadreply();
            Returnreply();
            Reply();
            var replyarea = document.querySelectorAll('.reply');
            if (window.localStorage.getItem('role') == 'student') {
                for (let a = 0; a < replyarea.length; a++)
                    replyarea[a].style.display = 'none';
            }
        })
    }

    //封装一个点击盒子展开评论的函数
    function Spreadreply() {
        var div1 = document.querySelectorAll('.container');
        var rarea = document.querySelectorAll('.answerarea');
        var li3 = document.querySelectorAll('.c1');
        for (let t = 0; t < div1.length; t++) {
            div1[t].onclick = function() {
                rarea[t].style.display = 'block';
                li3[t].className = '';
            }
        }
    }

    function Returnreply() {
        var return1 = document.querySelectorAll('.return');
        var rarea = document.querySelectorAll('.answerarea');
        var edit = document.querySelectorAll('.edittip1');
        var cancelpost = document.querySelectorAll('.cancelpost');
        var li3 = document.querySelectorAll('.c1');
        for (let t = 0; t < return1.length; t++) {
            return1[t].onclick = function() {
                rarea[t].style.display = 'none';
                li3[t].className = 'c1';
            }
            cancelpost[t].onclick = function() {
                edit[t].value = '';
                $('.aftertips').innerHTML = '取消成功';
                successtip();
            }
        }
    }

    function Reply() {
        var postbtn = document.querySelectorAll('.postreply');
        var container = document.querySelectorAll('.container');
        var edit = document.querySelectorAll('.edittip1');
        for (let t = 0; t < postbtn.length; t++) {
            postbtn[t].onclick = function() {
                told = container[t].getAttribute('toId');
                qid = container[t].getAttribute('questionId');
                content = edit[t].value;
                Postreply(told, qid, content);
            }
        }
    }
    //发送回复
    function Postreply(told1, qid1, content1) {
        axios({
            method: 'post',
            url: '/question/reply',
            data: {
                questionId: qid1,
                fromId: window.localStorage.getItem('id'),
                toId: told1,
                content: content1
            }
        }).then(response => {
            var res = response.data;
            console.log(res);

            if (res.code == 1) {
                $('.aftertips').innerHTML = res.msg;
                successtip();
                Getquestion();
            } else {
                $('.aftertips').innerHTML = res.msg;
                errtip();
            }
        })
    }
    //定义一个分割时间的函数
    function timeOperation(time) {
        // 获取动态发布的时间对象
        let dynamicTime = new Date(`${time.substr(0, 10)} ${time.substr(11, 8)}`);
        // 获取最新的北京时间
        let bjt = new Date(dynamicTime.getTime());
        // 处理时间
        let todayTime = new Date();
        let todayDate =
            todayTime.getFullYear() +
            "-" +
            (todayTime.getMonth() + 1) +
            "-" +
            todayTime.getDate();
        // 获取今天零时的时间
        let today = new Date(todayDate).getTime();
        // 显示时间
        let displayTime = "";
        let hour = bjt.getHours() > 9 ? bjt.getHours() : "0" + bjt.getHours();
        let minute = bjt.getMinutes() > 9 ? bjt.getMinutes() : "0" + bjt.getMinutes();
        let socond = bjt.getSeconds() > 9 ? bjt.getSeconds() : "0" + bjt.getSeconds();
        //alert(dynamicTime);
        if (bjt.getTime() > today) {
            displayTime = `今天 ${hour}:${minute}:${socond}`;
        } else if (bjt.getTime() > today - 86400000) {
            displayTime = `昨天 ${hour}:${minute}:${socond}`;
        } else if (bjt.getTime() > today - 172800000) {
            displayTime = `前天 ${hour}:${minute}:${socond}`;
        } else {
            displayTime = `${bjt.getFullYear()}年${
        bjt.getMonth() + 1
      }月${bjt.getDate()}日${hour}:${minute}:${socond}`;
        }
        return displayTime;
    }
    //二维码显示
    var wechat = document.querySelector('.social-item-img');
    var qr_code = document.querySelector('.qr-wrapper');
    wechat.addEventListener('mouseover', function() {
        qr_code.style.display = 'block';
    })
    wechat.addEventListener('mouseout', function() {
        qr_code.style.display = 'none';
    })
    stuquestion();
    //学生发布提问
    function stuquestion() {

        postbtn.addEventListener('click', function() {
            axios({
                method: 'post',
                url: '/question/ask',
                data: {
                    fromId: window.localStorage.getItem('id'),
                    content: postcontent.value
                }

            }).then(response => {
                var res = response.data;
                if (res.code == 1) {
                    console.log(res);
                    $('.aftertips').innerHTML = '发布成功！';
                    successtip();
                    Getquestion();
                } else {
                    console.log(res);
                    $('.aftertips').innerHTML = '仅学生权限！';
                    errtip();
                }
            })

        })
    }

    function Ifbuy() {
        axios({
            method: 'post',
            url: '/course/hasBuyCourse',
            data: {
                userId: window.localStorage.getItem('id'),
                courseId: window.localStorage.getItem('courseid')
            }
        }).then(res => {
            console.log(res.data);
            if (res.data.msg == '已经购买了该课程') {
                window.location.href = '../course-details/course-details-three.html';
            } else {
                window.location.assign('../course-details/course-details-two.html');
                console.log('1');
            }
        })
    }

}